package com.lvchen.ui.fourfunction.photograph;


import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.lvchen.R;
import com.lvchen.common.base.AppManager;
import com.lvchen.common.base.BaseActivity;
import com.lvchen.common.utils.DisyplayUtils;


public class MyCameraActivity extends BaseActivity implements CameraInterface.CamOpenOverCallback, OnClickListener, CameraInterface.TransmitDataCallback {
    private CameraSurfaceView camera_surfaceview = null;
    private Button btn_okphoto, btn_cancalphoto, btn_surephoto;
    private MaskView view_mask = null;
    private float previewRate = -1f;
    private int DST_CENTER_RECT_WIDTH = 0; //单位是dip
    private int DST_CENTER_RECT_HEIGHT = 0;//单位是dip
    private Point rectPictureSize = null;
    private int flag = -1;
    private ImageView img_upload_idcard;
    private ImageView img_back;
    private Drawable drawable;
    private final Rect viewRect = new Rect();
    private String fileaddress = "";

    public static final int MYCAMERA = 666;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //一定要取消状态栏,否则坐标对不齐
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_mycamera);
        initUI();
        initViewParams();
        CameraInterface.getInstance().setContext(this);
        CameraInterface.getInstance().setTransmitDataCallback(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        Thread openThread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                CameraInterface.getInstance().doOpenCamera(MyCameraActivity.this);
            }
        };
        openThread.start();
        btn_okphoto.setVisibility(View.VISIBLE);
        btn_surephoto.setVisibility(View.GONE);
        btn_cancalphoto.setVisibility(View.GONE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        CameraInterface.getInstance().doStopCamera();
    }

    private void initUI() {
        camera_surfaceview = (CameraSurfaceView) findViewById(R.id.camera_surfaceview);
        view_mask = (MaskView) findViewById(R.id.view_mask);
        btn_okphoto = (Button) findViewById(R.id.btn_okphoto);
        btn_cancalphoto = (Button) findViewById(R.id.btn_cancalphoto);
        btn_surephoto = (Button) findViewById(R.id.btn_surephoto);
        img_upload_idcard = (ImageView) findViewById(R.id.img_upload_idcard);
        img_back = (ImageView) findViewById(R.id.img_back);

        btn_okphoto.setOnClickListener(this);
        btn_cancalphoto.setOnClickListener(this);
        btn_surephoto.setOnClickListener(this);
        img_back.setOnClickListener(this);

        flag = getIntent().getIntExtra("flag", -1);

        CameraInterface.getInstance().setFlag(flag);

        if (flag == 1) {
            drawable = getResources().getDrawable(R.mipmap.uploadidcardbg);
        } else if (flag == 2) {
            drawable = getResources().getDrawable(R.mipmap.uploadidcardbg_back);
        }

        img_upload_idcard.setImageDrawable(drawable);


    }

    private void initViewParams() {
        LayoutParams params = camera_surfaceview.getLayoutParams();
        Point p = DisyplayUtils.getScreenMetrics(this);
        params.width = p.x;
        params.height = p.y;
        previewRate = DisyplayUtils.getScreenRate(this); //默认全屏的比例预览
        camera_surfaceview.setLayoutParams(params);
        LayoutParams p2 = btn_okphoto.getLayoutParams();
        p2.width = DisyplayUtils.dip2px(this, 80);
        p2.height = DisyplayUtils.dip2px(this, 80);
        btn_okphoto.setLayoutParams(p2);

    }

    @Override
    public void cameraHasOpened() {
        SurfaceHolder holder = camera_surfaceview.getSurfaceHolder();
        CameraInterface.getInstance().doStartPreview(holder, previewRate);
        getcoordinate();
        if (view_mask != null) {
            view_mask.setCenterRect(viewRect);
        }
    }

    private void getcoordinate() {

        img_upload_idcard.post(new Runnable() {
            @Override
            public void run() {
                img_upload_idcard.getGlobalVisibleRect(viewRect);
                String zuobiao = viewRect.toString().substring(5, viewRect.toString().length() - 1).replaceAll("-", ",").replaceAll(" ", "");
                String list[] = zuobiao.split(",");
                String top = list[1];
                String bottom = list[3];
                String left = list[0];
                String right = list[2];
                DST_CENTER_RECT_WIDTH = Integer.valueOf(right) - Integer.valueOf(left);
                DST_CENTER_RECT_HEIGHT = Integer.valueOf(bottom) - Integer.valueOf(top);
                System.out.println("==宽==" + DST_CENTER_RECT_WIDTH);
                System.out.println("==高==" + DST_CENTER_RECT_HEIGHT);
                System.out.println("==矩阵==" + viewRect.toString());

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_okphoto://
                btn_okphoto.setEnabled(false);
                if (rectPictureSize == null) {
                    rectPictureSize = createCenterPictureRect(DST_CENTER_RECT_WIDTH, DST_CENTER_RECT_HEIGHT);
                }
                CameraInterface.getInstance().doTakePicture(rectPictureSize.x, rectPictureSize.y);
                break;
            case R.id.btn_cancalphoto://
                btn_okphoto.setEnabled(true);
                Thread openThread = new Thread() {
                    public void run() {
                        CameraInterface.getInstance().againPreview();
                    }
                };
                openThread.start();
                btn_okphoto.setVisibility(View.VISIBLE);
                btn_surephoto.setVisibility(View.GONE);
                btn_cancalphoto.setVisibility(View.GONE);
                break;
            case R.id.btn_surephoto://
                CameraInterface.getInstance().doStopCamera();
                btn_okphoto.setVisibility(View.GONE);
                btn_cancalphoto.setVisibility(View.VISIBLE);
                btn_surephoto.setVisibility(View.VISIBLE);

                Intent intent = new Intent(MyCameraActivity.this, TakePhotoActivity.class);
                intent.putExtra("flag", flag);
                intent.putExtra("fileaddress", fileaddress);
                setResult(MYCAMERA, intent);
                AppManager.getAppManager().finishActivity();

                break;
            case R.id.img_back://返回上一页
                CameraInterface.getInstance().doStopCamera();
                AppManager.getAppManager().finishActivity();
                break;
        }
    }

    /**
     * 生成拍照后图片的中间矩形的宽度和高度
     *
     * @param w 屏幕上的矩形宽度，单位px
     * @param h 屏幕上的矩形高度，单位px
     * @return
     */
    private Point createCenterPictureRect(int w, int h) {
        int wScreen = DisyplayUtils.getScreenMetrics(this).x;
        int hScreen = DisyplayUtils.getScreenMetrics(this).y;
        int wSavePicture = CameraInterface.getInstance().doGetPrictureSize().y; //因为图片旋转了，所以此处宽高换位
        int hSavePicture = CameraInterface.getInstance().doGetPrictureSize().x; //因为图片旋转了，所以此处宽高换位
        float wRate = (float) (wSavePicture) / (float) (wScreen);
        float hRate = (float) (hSavePicture) / (float) (hScreen);
        float rate = (wRate <= hRate) ? wRate : hRate;//也可以按照最小比率计算
        int wRectPicture = (int) (w * wRate);
        int hRectPicture = (int) (h * hRate);
        return new Point(wRectPicture, hRectPicture);
    }

    @Override
    public void TransmitData(String fileN) {
        fileaddress = fileN;
        btn_okphoto.setVisibility(View.GONE);
        btn_surephoto.setVisibility(View.VISIBLE);
        btn_cancalphoto.setVisibility(View.VISIBLE);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            CameraInterface.getInstance().doStopCamera();
            AppManager.getAppManager().finishActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}